import {
  getDetail,
  getRecommends,
  GoodsBaseInfo,
  ShopInfo,
  ParamInfo,
} from "../../service/detail.js";

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    iid: "",
    topImages: [],
    baseInfo: {},
    shopInfo: {},
    detailInfo: {},
    paramInfo: {},
    commentInfo: {},
    recommends: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取 iid
    this.setData({
      iid: options.iid,
    });

    this._getDetail();

    this._getRecommends();
  },

  _getDetail() {
    getDetail(this.data.iid).then((res) => {
      const data = res.data.result;
      // 顶部图片
      const topImages = data.itemInfo.topImages;

      const baseInfo = new GoodsBaseInfo(
        data.itemInfo,
        data.columns,
        data.shopInfo.services
      );

      const shopInfo = new ShopInfo(data.shopInfo);

      const detailInfo = data.detailInfo;

      const paramInfo = new ParamInfo(
        data.itemParams.info,
        data.itemParams.rule
      );

      let commentInfo = {};
      if (data.rate && data.rate.cRate > 0) {
        commentInfo = data.rate.list[0];
      }

      this.setData({
        topImages: topImages,
        baseInfo,
        baseInfo,
        shopInfo: shopInfo,
        detailInfo: detailInfo,
        paramInfo: paramInfo,
        commentInfo: commentInfo,
      });
    });
  },

  _getRecommends() {
    getRecommends().then((res) => {
      this.setData({
        recommends: res.data.data.list,
      });
    });
  },

  onAddCart() {
    // 获取商品对象
    const obj = {};
    obj.iid = this.data.iid;
    obj.imgURL = this.data.topImages[0];
    obj.title = this.data.baseInfo.title;
    obj.desc = this.data.baseInfo.desc;
    obj.price = this.data.baseInfo.newPrice;

    // 加入购物车列表
    app.addToCart(obj);

    // 加入成功提示
    wx.showToast({
      title: "加入购物车成功",
    });
  },
});
